import { ErrorCode } from "../../src/config/ErrorCode";
import { Md5Helper } from "../../src/engine/utils/Md5Helper";
import { ResponseModel } from "../../src/model/ResponseModel";

export class GmUserModel {

    private static userMap: Map<string, GmUserModel> = new Map<string, GmUserModel>()
        .set("jhao", new GmUserModel(0, "jhao", "666666")) //




    private static session: Map<string, number> = new Map<string, number>();

    public userId: number;
    public userName: string;
    public pass: string;
    public token:string

    constructor(userId: number = 0, userName: string = "", pass: string = "") {
        this.userId = userId;
        this.userName = userName;
        this.pass = pass;
    }


    public static async checkLogin(userName: string, pass: string) {
        let respModel: ResponseModel = new ResponseModel()
        respModel.code = ErrorCode.Code.Suc
        if (this.userMap.has(userName)) {
            let model: GmUserModel = this.userMap.get(userName);
            if (model.pass == pass) {
                let token: string = Md5Helper.createToken(userName);
                model.token = token
                respModel.data = model
                this.removeSession(model.userId);
                this.insertSession(token, model.userId)
            } else {
                respModel.code = ErrorCode.Code.LoginError_NoPass
                respModel.msg = "密码不对"
            }
        } else {
            respModel.code = ErrorCode.Code.LoginError_NoPass
            respModel.msg = "用户不存在"
        }
        return respModel;
    }

    private static removeSession(userId: number) {
        this.session.forEach((value: number, key: string) => {
            if (value == userId) {
                this.session.delete(key)
                return;
            }
        });
    }

    private static insertSession(token: string, userId: number) {
        this.session.set(token, userId);
    }

    public static hasSession(token: string) {
        return this.session.has(token);
    }

    public static getUserByToken(token: string) {
        if (this.session.has(token)) {
            let userId: number = this.session.get(token)
            let user: GmUserModel = null
            this.userMap.forEach((value: GmUserModel, key: string) => {
                if (value.userId == userId) {
                    user = value;
                    return user;
                }
            });
            return user
        }
    }


}